package com.timu.cookie.basic;

import com.sun.deploy.net.HttpResponse;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.java2d.pipe.AAShapePipe;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class CookieController {
    @RequestMapping("path1/cookie")
    public String cookie1(HttpServletRequest request, HttpServletResponse response){
        Object count = request.getSession().getAttribute("count");
        int i = Integer.parseInt(count.toString());

        //保存
        int result=i;
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName()+","+cookie.getValue()+","+cookie.getPath()+","+cookie.getDomain()+","+cookie.getSecure()+","+cookie.isHttpOnly());
            }
        }else{
            System.out.println("cookie为空");
        }

        //设置cookie
        Cookie cookie = new Cookie("mycookie",String.valueOf(System.currentTimeMillis()));
        cookie.setHttpOnly(false);
        cookie.setMaxAge(60*60);
        cookie.setSecure(false);//如果尾true,仅支持https
        //更改path完成访问path2携带cookie的过程。
        cookie.setPath("/path2");
        //cookie.setDomain("www.baidu.com");

        response.addCookie(cookie);


        i++;
        request.getSession().setAttribute("count", i);
        System.out.println("helloworld");
        return "第"+result+"次访问";
    }

    @RequestMapping("setCount")
    public String setcount(HttpServletRequest request){
        request.getSession().setAttribute("count",1);
        return "设置成功";

    }

    //访问该url以后是否能将cookie带过来
    @RequestMapping("path2/cookie")
    public String cookie2(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName()+","+cookie.getValue()+","+cookie.getPath()+","+cookie.getDomain()+","+cookie.getSecure()+","+cookie.isHttpOnly());
            }
        }else {
            System.out.println("Cookie为空！");
        }
        return "访问第2个方法";

    }




}
